package com.d3works.apps.stock.db.repo;

import com.d3works.apps.base.db.Product;
import com.d3works.apps.base.db.repo.ProductBaseRepository;
import com.d3works.apps.stock.db.repo.product.ProductStockRepositoryPopulate;
import com.d3works.apps.stock.db.repo.product.ProductStockRepositorySave;
import com.google.inject.Inject;
import java.math.BigDecimal;
import java.util.Map;

public class ProductStockRepository extends ProductBaseRepository {

  @Inject protected ProductStockRepositorySave productStockRepositorySave;
  @Inject protected ProductStockRepositoryPopulate productStockRepositoryPopulate;

  @Override
  public Product save(Product product) {
    productStockRepositorySave.addProductCompanies(product);
    return super.save(product);
  }

  @Override
  public Map<String, Object> populate(Map<String, Object> json, Map<String, Object> context) {

    if (Boolean.TRUE.equals(context.get("_xFillProductAvailableQty"))
        || (context.get("_parent") != null
            && Boolean.TRUE.equals(
                ((Map) context.get("_parent")).get("_xFillProductAvailableQty")))) {
      productStockRepositoryPopulate.setAvailableQty(json, context);
    }

    if (context.containsKey("fromStockWizard")) {
      productStockRepositoryPopulate.fillFromStockWizard(json, context);
    }

    return json;
  }

  @Override
  public Product copy(Product product, boolean deep) {
    Product copy = super.copy(product, deep);
    copy.setAvgPrice(BigDecimal.ZERO);
    return copy;
  }
}
